﻿using System.Linq.Expressions;
using K9Nano.Application.Dtos;
using K9Nano.Domain.Entities;
using K9Nano.Extensions;

#pragma warning disable IDE0130 // 命名空间与文件夹结构不匹配
namespace K9Nano.Application.Authentication;
#pragma warning restore IDE0130 // 命名空间与文件夹结构不匹配

public class UserQueryDto<TUser> : PagedQueryDto<TUser>
    where TUser : UserBase
{
    public string? Username { get; set; }
    public string? Name { get; set; }
    public string? Phone { get; set; }
    public long? OrganizationId { get; set; }

    public override Expression<Func<TUser, bool>>? GetPredicate()
    {
        Expression<Func<TUser, bool>>? predicate = null;

        if (!string.IsNullOrWhiteSpace(Username))
        {
            predicate = a => a.Username.Contains(Username);
        }

        if (!string.IsNullOrWhiteSpace(Name))
        {
            if (predicate is null)
            {
                predicate = a => a.Name.Contains(Name);
            }
            else
            {
                predicate = predicate.AndAlso(a => a.Name.Contains(Name));
            }
        }

        if (!string.IsNullOrWhiteSpace(Phone))
        {
            if (predicate is null)
            {
                predicate = a => a.Phone == Phone;
            }
            else
            {
                predicate = predicate.AndAlso(a => a.Phone == Phone);
            }
        }

        if (OrganizationId == 0)
        {
            if (predicate is null)
            {
                predicate = a => a.OrganizationId == null;
            }
            else
            {
                predicate = predicate.AndAlso(a => a.OrganizationId == null);
            }
        }
        else if (OrganizationId > 0)
        {
            if (predicate is null)
            {
                predicate = a => a.OrganizationId == OrganizationId;
            }
            else
            {
                predicate = predicate.AndAlso(a => a.OrganizationId == OrganizationId);
            }
        }

        return predicate;
    }
}